package com.apbetioli.mapr.client;

/**
 *
 * @author alexandre
 */
public class XMLBeautifier {

    public static String makeItBeautiful( final String xml ) {
        
        String[] pieces = xml.split("><");
        
        if( pieces.length <= 2 )
            return xml;
        
        StringBuffer pretty = new StringBuffer(pieces[0] + ">\n<" + pieces[1]);

        int tab = 0;
        boolean lastDecreased = false;
        
        for( int i = 2; i < pieces.length; i++ ) {

            if( pieces[i].startsWith("/") ) {
                tab--;            
                lastDecreased = true;
            }
            else {
                if( lastDecreased )
                    lastDecreased = false;
                else {
                    if ( ! pieces[i-1].contains("</") )
                        tab++;
                }
                    
            }
            
            pretty.append(">\n");
            for( int t = 0; t < tab; t++ ) {
                pretty.append("\t");
            }
            pretty.append("<");
            pretty.append(pieces[i]);

        }
        
        return pretty.toString();
    }
    
}
